#include "GameCore/Renderer.h"
#include "Body.h"
#include "PhysicsUtils.h"
#include "PhysicsDebugDrawer.h"

using namespace cmn;

Body::Body( b2World* world, const b2BodyType type, const Transform& pos, const Transform& vel, const ReusableBodyDef* reusableBodyDef, const TextureInfo* texInfo ) :
	m_texInfo( texInfo )
{
	m_world = world;

	b2BodyDef* bodyDef = new b2BodyDef();
	bodyDef->position = ToB2Vec2( pos.Vec );
	bodyDef->angle = pos.Rot;
	bodyDef->linearVelocity = ToB2Vec2( vel.Vec );
	bodyDef->angularVelocity = vel.Rot;
	bodyDef->type = type;

	m_body = m_world->CreateBody( bodyDef );
	b2MassData* massData = new b2MassData();
	massData->I = 1.0f;
	massData->mass = 1.0f;

	m_body->SetMassData( massData );
	delete massData;

	for( IteratorPtr<b2FixtureDef*> fixturesIter( reusableBodyDef->GetFixtureDefs() );
			!fixturesIter.IsEnd();
			fixturesIter.Next() )
	{
		b2FixtureDef* fixtureDef = fixturesIter.Current();
		m_body->CreateFixture( fixtureDef );
	}
	m_body->SetMassData( reusableBodyDef->GetMassData() );
}

Body::~Body() {
	m_world->DestroyBody( m_body );
}

void Body::Draw() const {
	PhysicsDebugDrawer drawer(
		core::Color( 0.2f, 1.0f, 0.2f ),
		core::Color( 0.2f, 1.0f, 0.2f, 0.2f ) );

	drawer.DrawBody( m_body );

	Transform bodyPos = ToTransform( m_body->GetTransform() );
	Transform texPos = bodyPos * m_texInfo->GetPosition();

	core::Renderer::DrawTexture(
		m_texInfo->GetImage(),
		texPos,
		m_texInfo->GetWidth(),
		m_texInfo->GetHeight() );
}
